package cn.kgc.test.util;

import cn.kgc.test.annotation.Test;

import java.lang.reflect.Field;
import java.lang.reflect.Method;

/**
 * @Author: 课工场
 * @Version: v1.0  2023/2/26
 * @Description:
 * 1. 实现调用对象中的方法
 * 2.实现对象中的赋值操作
 */
public class AllUtils {


    /*
    * Object object  目标对象
    * String methodName  被调用的方法名
    * Class[] paramType  调用方法的参数类型
    * Object ...params  调用方法传入的参数
    * */
    public static Object invokeMethod(Object object,String methodName,Class[] paramType,Object ...params){

        Class clazz = object.getClass();
        Object invoke = null;
        try {
            Method declaredMethod = clazz.getDeclaredMethod(methodName, paramType);
            declaredMethod.setAccessible(true);

            invoke = declaredMethod.invoke(object, params);


        } catch (Exception e) {
            e.printStackTrace();
        }

        return invoke;
    }


    public static  void setValue(Object object,String field,Object value){

        Class clazz = object.getClass();
        try {
            Field declaredField = clazz.getDeclaredField(field);
            declaredField.setAccessible(true);
            declaredField.set(object, value);
        } catch (Exception e) {
            e.printStackTrace();
        }

    }



    // 调用被Test标识的所有方法
    public static void  invokeMethodByTestAnnotation(Class clazz) throws Exception {

        Method[] declaredMethods = clazz.getDeclaredMethods();
        for (Method declaredMethod : declaredMethods) {
            declaredMethod.setAccessible(true);
            Test annotation = declaredMethod.getAnnotation(Test.class);
            if(annotation!=null) {
                Object o = clazz.getDeclaredConstructor().newInstance();
                declaredMethod.invoke(o);
            }
        }

    }
}
